//定位当前城市
//当前城市名称 浙江省杭州市
// console.log(returnCitySN.cname);

$(function() {
    // 从缓存中获取数据（在登录成功后会将当前用户和用户令牌放入缓存中）
    const user = JSON.parse(window.sessionStorage.getItem("user"));
    const token = window.sessionStorage.getItem("token");
    if(user == null || token == null){
        alert("请先登录");
        window.location.href = "../html/welcome.html";
    }

    //导航球 下拉
    $("#gooey").gooeymenu({
        bgColor: "rgba(79,117,167,0.4)",
        contentColor: "white",
        style: "vertical",
        horizontal: {
            menuItemPosition: "glue"
        },
        vertical: {
            menuItemPosition: "spaced",
            direction: "down"
        },
        circle: {
            radius: 90
        },
        margin: "small",
        size: 70,
        bounce: true,
        bounceLength: "small",
        transitionStep: 100,
        hover: "rgba(79, 117, 167, 0.6)"
    });

    //新闻榜单滚动条
    $("#left").scrollBar({
        barWidth: 5, //滚动条的宽度(这里根据需要写数值即可，不设置是10,即默认10px)
        position: "y", //写“x”代表只出水平滚动条，写“y”表示只出垂直滚动条，写“x,y”则出水平和垂直滚动条（只有在内容超出容器时才出现滚动条）
        wheelDis: 20 //滚轮滚动一次向下或向上滚动的距离，默认是15，可根据需要修改数值
    });

    //获取Top新闻数据
    getTop10News(token);

    //获取轮播图信息
    getAllPictureNews(token);

    //获取公告栏数据
    getAllNotice(token);

    //关闭页面时调用logout方法，退出当前登录用户
    $(window).unload(function(){
        $.ajax({
            type:"POST",
            contentType:"application/json",
            xhrFields: {
                withCredentials: true
            },
            crossDomain: true,
            url :"http://localhost:2082/logout?username=" + user.username
        })
    });
});


//获取轮播图ajax
function getAllPictureNews(token){
    $.ajax({
        url: "http://localhost:2082/picture/all",
        type: "GET",
        headers: {
            "token":token
        },
        success: function (data,status,xhr) {
            //若用户认证过期，后端返回的响应头中会有一个token字段，值为overdue
            const responseToken = xhr.getResponseHeader("token");
            if(responseToken == "overdue"){
                $('#addTucao').modal('hide');
                alert("用户认证已过期，请重新登录");
                window.location.href = "../html/welcome.html";
            }else {
                let result = JSON.stringify(data);
                result = eval("("+result+")");
                //操作成功
                if(result.code == 200){
                    const pictureData = result.data;
                    for (let i = 1; i <= 3; i++) {
                        const title = JSON.stringify(pictureData[i-1].title);
                        const content = JSON.stringify(pictureData[i-1].content);
                        //先清空
                        $("#imgTitle"+i).empty();
                        $("#imgContent"+i).empty();
                        //再赋值
                        $("#imgTitle"+i).html(title.replace(/\"/g, ""));
                        $("#imgContent"+i).html(content.replace(/\"/g, ""));
                    }
                }
                //操作失败
                else if(result.code == 500){
                    spop({
                        template: result.msg,
                        position  : 'top-center',
                        group: "submit-satus",
                        style: "fail",
                        autoclose: 2000
                    });
                }
            }

        }
    });
}

//获取头条Top新闻ajax
function getTop10News(token){
    $.ajax({
        type: "GET",
        contentType: "application/json",
        headers: {
            "token":token
        },
        url: "http://localhost:2082/news",
        success: function(data) {
            let responseData = JSON.stringify(data);
            responseData = eval("("+responseData+")");
            let resultData = responseData.result;
            const newsData = eval("("+JSON.stringify(resultData)+")").data;

            for (let i = 1; i <= 10; i++) {
                //新闻图片
                const newsImgUrl = JSON.stringify(newsData[i].thumbnail_pic_s);
                // console.log("newsImgUrl=" + newsImgUrl);
                //新闻链接
                const newsHref = JSON.stringify(newsData[i].url);
                // console.log("newsHref=" + newsHref);
                //新闻标题
                const newsTitle = JSON.stringify(newsData[i].title);
                //新闻出版社
                const newsFrom = JSON.stringify(newsData[i].author_name);
                //新闻发表时间
                const newsTime = JSON.stringify(newsData[i].date);

                $("#newsImg" + i).attr("src",newsImgUrl.replace(/^\"|\"$/g,''));
                $("#newsHref" + i).attr("href",newsHref.replace(/^\"|\"$/g,''));
                $("#newsTitle" + i).html(newsTitle.replace(/^\"|\"$/g,''));
                $("#newsFrom" + i).html(newsFrom.replace(/^\"|\"$/g,''));
                $("#newsTime" + i).html(newsTime.replace(/^\"|\"$/g,''));
            }
        }
    })
}

//获取公告栏数据ajax
function getAllNotice(token){
    $.ajax({
        url: "http://localhost:2082/notice",
        type: "GET",
        headers: {
            "token":token
        },
        success: function (data,status,xhr) {
            //若用户认证过期，后端返回的响应头中会有一个token字段，值为overdue
            const responseToken = xhr.getResponseHeader("token");
            if(responseToken == "overdue"){
                alert("用户认证已过期，请重新登录");
                window.location.href = "../html/welcome.html";
            }else {
                let result = JSON.stringify(data);
                result = eval("("+result+")");
                //操作成功
                if(result.code == 200){
                    const noticeData = result.data;
                    let updateTime = "2021-4-21 00:00:00";
                    for (let i = 1; i <= 5; i++) {
                        const notice = JSON.stringify(noticeData[i-1].notice);
                        const updateTimeFromData = JSON.stringify(noticeData[i-1].updateTime);
                        //先清空
                        $("#notice"+i).empty();
                        //再赋值
                        $("#notice"+i).html(notice.replace(/\"/g, ""));

                        const forOut = new Date(updateTime.replace("-", "/").replace("-", "/"));
                        const forIn = new Date(renderTime(updateTimeFromData.replace(/^\"|\"$/g,'')).replace("-", "/").replace("-", "/"));
                        if(forIn > forOut){
                            updateTime = renderTime(updateTimeFromData.replace(/^\"|\"$/g,''));
                        }
                    }
                    $("#noticeTime").html(updateTime);
                }
                //操作失败
                else if(result.code == 500){
                    spop({
                        template: result.msg,
                        position  : 'top-center',
                        group: "submit-satus",
                        style: "fail",
                        autoclose: 2000
                    });
                }
            }

        }
    });
}

// 时间格式转换
function renderTime(date) {
    var dateee = new Date(date).toJSON();
    // return new Date(+new Date(dateee) + 8 * 3600 * 1000).toISOString().replace(/T/g, ' ').replace(/\.[\d]{3}Z/, '');
    return new Date(+new Date(dateee)).toISOString().replace(/T/g, ' ').replace(/\.[\d]{3}Z/, '');
}

//背景 雨玻璃
function run() {
    var image = document.getElementById('background');
    image.onload = function() {
        var engine = new RainyDay({
            image: this,
            blur: 10,
            opacity: 1
        });
        engine.rain([
            [1, 2, 15000]
        ]);
        engine.rain([
            [3, 3, 0.88],
            [5, 5, 0.9],
            [6, 2, 1]
        ], 100);
    };
    image.crossOrigin = 'anonymous';
    image.src = '../img/bg3.jpg';
}





